﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace Mongaba.Core.Util
{
    public class TextBoxStreamWriter : TextWriter
    {

            
            TextBox _output = null;

            public TextBoxStreamWriter(TextBox output)
            {
                _output = output;
                _output.MaxLength = 30000;

            }
                  
            public override void WriteLine(string value)
            {
                base.WriteLine(value);

                if (!PauseDebug)
                {
                    if ((value.Length + _output.Text.Length) > _output.MaxLength)
                    {
                        int newIndex = 0;
                        int length = 0;
                        foreach (string s in _output.Lines)
                        {
                            if ((s.Length + length + value.Length) > _output.MaxLength)
                            {
                                break;
                            }
                            else
                            {
                                length += s.Length;
                            }

                            newIndex++;
                        }
                        _output.Lines = _output.Lines.Reverse().TakeWhile((x, index) => index < newIndex).Reverse().ToArray();
                       
                    }
                    
                    _output.Text += (string.Format("{0} - {1} \r\n", DateTime.Now, value));

                    if (AutoScroll)
                    {
                        _output.SelectionStart = _output.Text.Length;
                        _output.ScrollToCaret();
                    }
                } 
            }
            public override void WriteLine()
            {
                base.WriteLine();
                _output.AppendText("\r\n");
            }
            public void Clear()
            {
                _output.Text = string.Empty;
            }
            public override Encoding Encoding
            {
                get { return System.Text.Encoding.UTF8; }
            }

            public bool AutoScroll
            {
                get;
                set;
            }

            public bool PauseDebug
            {
                get;
                set;

            }
        }
    
}
